package org.itboys.core.service.mongo.front;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.tray.SundayTrayMapper;
import org.itboys.core.dto.index.SundayIndexDTO;
import org.itboys.core.entity.mongo.SundayStore;
import org.itboys.core.entity.mysql.tray.SundayTray;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/12/27
 * @Description：仓库
 */
@Service
public class SundayFrontStoreService extends BaseMongoService<SundayStore> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayStore> getEntityClass() {
        return SundayStore.class;
    }

    @Autowired
    private SundayTrayMapper trayMapper;

    public List<SundayIndexDTO> index(Long cityId) {
        List<SundayIndexDTO> result = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cityId", cityId);
        List<SundayStore> stores = super.list(param);
        if (ListUtil.isNull(stores)) return result;
        List<Long> storeIds = new ArrayList<>();
        for (SundayStore store : stores
                ) {
            storeIds.add(store.getId());
        }
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("storeId in", storeIds);
        List<SundayTray> trays = trayMapper.select(param);
        return packageIndexDTOs(stores,trays);
    }

    public List<SundayIndexDTO> packageIndexDTOs(List<SundayStore> stores, List<SundayTray> trays) {
        List<SundayIndexDTO> result=new ArrayList<>();
        if(ListUtil.isNull(stores)){
            return result;
        }
        for (SundayStore store:stores
             ) {
            SundayIndexDTO dto=new SundayIndexDTO();
            dto.setLatitude(store.getLatitude());
            dto.setLongitude(store.getLongitude());
            dto.setStoreId(store.getId());
            dto.setStoreName(store.getName());
            Integer storeNum=0;
            for (SundayTray tray:trays
                 ) {
                if(store.getId()==tray.getStoreId().longValue()){
                    storeNum++;
                }
            }
            dto.setStoreNum(storeNum);
            result.add(dto);
        }
        return result;
    }

}
